const rule = require("./rule");

const createControl = function ({
    tableName = "",
    projectName = "",
    method = ["List", "ListByQuery", "Add", "Edit", "Del"],
    table,
    isImport = true,
}) {
    const pkName = table.find(item => item.isPK == 1).name;
    return `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using iver.Entity;
using DBEntity;
${!isImport?"":`using NPOI.HSSF.UserModel;
//using NPOI.HPSF;
//using NPOI.POIFS.FileSystem;
//using NPOI.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
`}
namespace iver.Controllers
{
    public class ${projectName}Controller : ApiController
    {
        ${!method.some(item => item == "List") ? '' : `/// <summary>
        /// 得到列表
        /// </summary>
        [HttpPost]
        public ResResult ${projectName}List([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.${tableName}
                        orderby u.${pkName} descending
                        select u);
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        `}
        ${table.filter(item => item.fk).map(item => `
        /// <summary>
        /// 得到关联列表
        /// </summary>
        [HttpPost]
        public ResResult ${item.fk.tableName}List([FromBody]ReqList req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = (from u in db.${item.fk.tableName}
                        orderby u.id descending
                        select new {
                            u.${item.fk.pkName},
                            u.${item.fk.displayName},
                        });
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        `)}
        ${!method.some(item => item == "ListByQuery") ? '' : `public class Req${projectName}List : ReqList
        {
${table
                .filter(item => item.isPK == 0 && item.isSearch)
                .map(item => `\t\t\tpublic ${rule[item.typeName].type} ${item.name} { get; set; }`)
                .join("\n")}
${table
                .filter(item => item.fk)
                .map(item => `\t\t\tpublic string f${item.fk.displayName} { get; set; }`)
                .join("\n")}        
        }
        /// <summary>
        /// 得到列表通过条件
        /// </summary>
        [HttpPost]
        public ResResult ${projectName}ListByQuery([FromBody]Req${projectName}List req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
${table
                .filter(item => item.typeName == "datetime" && item.isSearch)
                .map(item => `
            DateTime? b_${item.name} = null;
            DateTime? e_${item.name} = null;
            if (req.${item.name} != null)
            {
                string[] temp = req.${item.name}.Split(',');
                DateTime bt = Convert.ToDateTime(temp[0]);
                DateTime et = Convert.ToDateTime(temp[1]);
                b_${item.name} = new DateTime(bt.Year, bt.Month, bt.Day, 0, 0, 0);
                e_${item.name} = new DateTime(et.Year, et.Month, et.Day, 23, 59, 59);
            }
        `)
                .join("\n")}              
            iverDB db = new iverDB();
            var list = (from u in db.${tableName}
                        ${table.filter(item => item.fk).map(item => `join j${item.fk.tableName} in db.${item.fk.tableName} on u.${item.name} equals j${item.fk.tableName}.${item.fk.pkName} into t${item.fk.tableName}
                        from f${item.fk.tableName} in t${item.fk.tableName}.DefaultIfEmpty()`).join("\n")}
                        orderby u.${pkName} descending
                        where
                            1== 1 
${table
                .filter(item => item.isPK == 0 && item.isSearch)
                .map(item => `\t\t\t\t\t\t${rule[item.typeName].query(item.name)}`)
                .join("\n")}
${table
                .filter(item => item.fk)
                .map(item => `\t\t\t\t\t\t&& (req.f${item.fk.displayName} == null ? 1 == 1 : f${item.fk.tableName}.${item.fk.displayName}.Contains(req.f${item.fk.displayName}))`)
                .join("\n")}        
                        select new
                        {
                            ${table.map(item => `u.${item.name},`).join("\n")}
                            ${table.filter(item => item.fk).map(item => `f${item.fk.displayName} = f${item.fk.tableName}.${item.fk.displayName},`).join("\n")}
                        });
            var arr = list.Skip(req.limit * (req.page - 1)).Take(req.limit);
            int count = list.Count();
            return new ResResult
            {
                success = true,
                result = new
                {
                    count,
                    arr,
                }
            };
        }
        `}
        ${!method.some(item => item == "Add") ? '' : `/// <summary>
        /// 添加
        /// </summary>
        [HttpPost]
        public ResResult ${projectName}Add([FromBody]${tableName} req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            db.${tableName}.Add(req);
            db.SaveChanges();
            Help.Log(authInfo, req.${pkName}.ToString());
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessAdd,
                result = new
                {
                    id = req.${pkName},
                },
            };
        }
        `}
        ${!method.some(item => item == "Edit") ? '' : `/// <summary>
        /// 编辑
        /// </summary>
        [HttpPost]
        public ResResult ${projectName}Edit([FromBody]${tableName} req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            ${tableName} model = db.${tableName}.FirstOrDefault(u => u.${pkName} == req.${pkName});
            if (model == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
${table.filter(item => item.isPK == 0).map(item => `\t\t\tmodel.${item.name} = req.${item.name} == null ? model.${item.name} : req.${item.name};`).join("\n")}
            int result = db.SaveChanges();
            Help.Log(authInfo, req.${pkName}.ToString());
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessEdit,
                result = new
                {
                    changeCount = result,
                },
            };
        }
        `}
        ${!method.some(item => item == "Del") ? '' : `/// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public ResResult ${projectName}Del([FromBody]ReqID<List<int>> req)
        {
            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            iverDB db = new iverDB();
            var list = db.${tableName}.Where(u => req.id.Contains(u.${pkName}));
            int delCount = list.Count();
            if (delCount == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                };
            }
            db.${tableName}.RemoveRange(list);
            db.SaveChanges();
            Help.Log(authInfo, Newtonsoft.Json.JsonConvert.SerializeObject(req.id));
            return new ResResult
            {
                success = true,
                rescode = ResCode.SuccessDel,
                result = new
                {
                    delCount,
                },
            };
        }
        ${!isImport ? "" : `
        /// <summary>
        /// excel导入参数
        /// </summary>
        public class ReqImport
        {
            public string label { get; set; }
            public string value { get; set; }
            public string type { get; set; }
        }
        /// <summary>
        /// excel导入
        /// </summary>
        [HttpPost]
        public ResResult importExcel()
        {

            AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            if (System.Web.HttpContext.Current.Request["jsonStr"] == null)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "无导入参数",

                };
            }
            IWorkbook workbook;
            string fileExt = System.IO.Path.GetExtension(System.Web.HttpContext.Current.Request.Files[0].FileName);
            if (!(fileExt.ToLower() == ".xls" || fileExt.ToLower() == ".xlsx"))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "文件格式错误",

                };
            }

            string jsonStr = System.Web.HttpContext.Current.Request["jsonStr"];
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<ReqImport> mylist = js.Deserialize<List<ReqImport>>(jsonStr);
            List<ReqImport> oldlist = new List<ReqImport>();
            ${table.filter(item => item.isPK == 0).map(item => `
            oldlist.Add(new ReqImport()
            {
                value = "${item.name}",
                type = "${item.typeName}",
            });`).join('')}
            List<ReqImport> dbList = new List<ReqImport>();
            for (int i = 0; i < oldlist.Count; i++)
            {
                for (int j = 0; j < mylist.Count; j++)
                {
                    if (mylist[j].value == oldlist[i].value)
                    {

                        dbList.Add(new ReqImport()
                        {
                            label = mylist[j].label,
                            value = oldlist[i].value,
                            type = oldlist[i].type,
                        });
                        break;
                    }
                }
            }

            if (fileExt == ".xls")
            {
                workbook = new HSSFWorkbook(System.Web.HttpContext.Current.Request.Files[0].InputStream);
            }
            else
            {
                workbook = new XSSFWorkbook(System.Web.HttpContext.Current.Request.Files[0].InputStream);
            }
            ISheet _sheet = workbook.GetSheetAt(0);
            List<ReqImport> flist = new List<ReqImport>();
            bool flag = false;
            for (int i = 0; i < _sheet.GetRow(0).Cells.Count; i++)
            {
                bool flaghas = false;
                for (int j = 0; j < dbList.Count; j++)
                {
                    if (dbList[j].label == _sheet.GetRow(0).Cells[i].ToString())
                    {
                        flaghas = true;
                        flist.Add(dbList[j]);
                        break;
                    }
                }
                if (!flaghas)
                {
                    flag = true;
                }
            }
            if (flag)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "导入格式错误",
                };
            }
            ////数组去重
            //for (int i = 0; i < flist.Count; i++)
            //{
            //    List<ReqImport> ll = flist.FindAll(p => p.value == flist[i].value);
            //    if (ll.Count > 1)
            //    {
            //        flist.Remove(ll[0]);
            //    }
            //}
            List<ReqImport> finalList = flist;
            List<${tableName}> list = new List<${tableName}>();
            for (int i = _sheet.LastRowNum ; i > 0; i--)
            {
                ${tableName} model = new ${tableName}();
                IRow row = _sheet.GetRow(i);
                IRow typeRow = _sheet.GetRow(0);
                for (int j = 0; j < row.LastCellNum; j++)
                {
                    List<ReqImport> rs = finalList.FindAll(p => p.label == typeRow.Cells[j].ToString());
                    string cellVal = row.Cells[j].ToString();
                    switch (rs[0].type)
                    {
                        case "int":
                            int int_v;
                            if (int.TryParse(cellVal, out int_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, int_v);
                            }
                            break;
                        case "datetime":
                            DateTime DateTime_v;
                            if (DateTime.TryParse(cellVal, out DateTime_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, DateTime_v);
                            }
                            break;
                        case "bit":
                            bool bool_v;
                            if (bool.TryParse(cellVal, out bool_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, bool_v);
                            }
                            break;
                        case "decimal":
                            decimal decimal_v;
                            if (decimal.TryParse(cellVal, out decimal_v))
                            {
                                model.GetType().GetProperty(rs[0].value).SetValue(model, decimal_v);
                            }
                            break;    
                        default:
                            model.GetType().GetProperty(rs[0].value).SetValue(model, cellVal);
                            break;
                    }
                }
                list.Add(model);
            }
            iverDB db = new iverDB();
            db.${tableName}.AddRange(list);
            int count = db.SaveChanges();
            Help.Log(authInfo, count.ToString());

            return new ResResult
            {
                success = true,
                result = finalList,
            };

        }
        `}
        ${table.filter(item => item.stringType == "img").length > 0 ? `/// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResResult uploadImg()
        {
            Entity.AuthInfo authInfo;
            if (!ReqBase.isAuth(out authInfo))
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailAuth,
                };
            }
            return Help.uploadfile("${projectName}", 3);
        }`: ""}
        `}
    }
}
  `;

}

module.exports = createControl;